觀前提醒:
連結:https://leetcode.com/problems/two-sum/
Given an array of integers numsand and integer target, return the indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1]
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
這題的概念,我認為不太難,就是直接歷遍整個 array,每次依序取出兩個數字作加法。只要兩數相加之和等於 target,那就直接 return 那兩數在 array 的位置就好。
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  for (let i = 0; i <= nums.length - 2; i++) {
    let x = nums[i];
    for (let j = i + 1; j <= nums.length - 1; j++) {
      let y = nums[j];
      if (x + y === target) {
        return [i, j];
      }
    }
  }
};
這應該算是新手刷題時,人人都會遇到的天下第一題吧?
基本上沒有做過這題,那你應該就不算是 LeetCode 人(戰 XDDDD
謝謝大家的收看,我們明天見(鞠躬
886~